/**
 * @Author: easten
 * @Created: 2024-08-14 23:54:19
 * @Description: 加脂机监测列表
 *
 */
import { IotDeviceData } from "_common/DataType";
import { IotPoint } from "_common/entity";
import dayjs from "dayjs";
import React, { useEffect, useState } from "react";
import {
  Button,
  Descriptions,
  Dialog,
  PrimaryTableCol,
  Progress,
  Table,
  TableProps,
  Tag,
} from "tdesign-react";
import greaseImg from "assets/iot-jzj.png";
import { ApiDevice, ApiRealtime } from "_common/api/iot";
import { AxiosInstance } from "axios";
type PointDataType = IotPoint & IotDeviceData & {};
type GreaseTableProps = {
  height?: number;
  dataList: PointDataType[];
  realData?: PointDataType;
  onSelect: (data: PointDataType) => void;
  facilityId?: number;
  axios: AxiosInstance;
};
const GreaseTable: React.FC<GreaseTableProps> = (props: GreaseTableProps) => {
  const { height, dataList, onSelect, axios, realData } = props;

  const [dataSource, setDataSource] = useState<PointDataType[]>([]);
  const [expandOnRowClick] = useState(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState(["2"]);
  const { DescriptionsItem } = Descriptions;
  const apiRealtime = new ApiRealtime(axios);
  const apiDevice = new ApiDevice(axios);

  const [progress, setProgress] = useState(0);
  // 定义是否正在加脂
  const [isRunning, setIsRunning] = useState(false);
  // 打开对话框
  const [visible, setVisible] = useState(false);
  // 是否加脂完成
  const [isFinish, setIsFinish] = useState(false);
  // 需要加脂的设备记录
  const [deviceCode, setDeviceCode] = useState<number>();
  // 记录一下下发记录的id 用于加脂完成后的查询
  const [recordId, setRecordId] = useState<number>();

  // 记录结果状态文本
  const [resultText, setResultText] = useState("操作完成");

  useEffect(() => {
    setDataSource(dataList);
    if (dataList) {
      apiRealtime.getAll().then((res) => {
        if (res && res.code == 200 && res.data) {
          res.data.forEach((realData) => {
            setDataSource((pre) => {
              return pre.map((item) => {
                if (item.deviceCode === realData.deviceCode) {
                  return { ...item, ...realData };
                }
                return item;
              });
            });
          });
        }
      });
    }
  }, [dataList]);

  useEffect(() => {
    if (realData) {
      setDataSource((pre) => {
        return pre.map((item) => {
          if (item.deviceCode === realData.deviceCode) {
            return { ...item, ...realData };
          }
          return item;
        });
      });
    }
  }, [realData]);

  // 执行加脂
  useEffect(() => {
    let timer: any;
    if (isRunning) {
      const startTime = Date.now();
      timer = setInterval(() => {
        const elapsedTime = Date.now() - startTime;
        const newProgress = Math.floor((elapsedTime / 40000) * 100); // 用 Math.floor 将进度值转换为整数
        if (newProgress >= 100) {
          setProgress(100);
          setIsRunning(false);
          clearInterval(timer);
          setIsFinish(true);
          getResult();
        } else {
          setProgress(newProgress);
        }
      }, 100); // 每100ms更新一次进度
    }
    return () => clearInterval(timer);
  }, [isRunning]);

  // 查询加脂结果
  const getResult = async () => {
    const response = await apiDevice.getGreaseResult(recordId);
    if (response && response.code == 200 && response.data) {
      if (response.data?.isComplete) {
        setResultText("加脂完成");
      } else {
        setResultText("加脂失败");
      }
    }
  };

  // 获取设备状态
  const getDeviceState = (row: PointDataType) => {
    // 0:正常，1：预警、2、报警、3：故障、4、离线
    let state = ["正常", "预警", "报警", "故障", "离线"];
    let color = ["#00a854", "#ffd600", "#f5222d", "#38BDAA", "#308EEA"];
    return (
      <Tag variant="outline" color={color[row.status ?? 4]}>
        {state[row.status ?? 4]}
      </Tag>
    );
  };

  // 表格定义
  const columns: PrimaryTableCol<PointDataType>[] = [
    {
      align: "left",
      width: 80,
      ellipsis: true,
      colKey: "orderNo",
      title: "序号",
      cell: ({ rowIndex }) => {
        return rowIndex + 1;
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "code",
      title: "测点编码",
      cell: ({ row }) => {
        return (
          <Button
            tag="a"
            variant="text"
            size="small"
            theme="primary"
            onClick={() => {
              /*  setVisible(true);
               */
            }}
          >
            {row.code}
          </Button>
        );
      },
    },
    {
      align: "left",
      ellipsis: true,
      colKey: "name",
      title: "测点名称",
    },
    /*  {
      align: "left",
      ellipsis: true,
      colKey: "location",
      title: "测点位置",
    }, */
    {
      align: "center",
      ellipsis: true,
      colKey: "deviceCode",
      title: "加脂机ID",
      width: 100,
      cell: ({ row }) => {
        return (
          <div
            className="flex flex-row items-center justify-center cursor-pointer"
            onClick={() => {
              onSelect(row);
            }}
          >
            <Tag variant="light-outline" theme="success">
              <span>{row?.deviceCode}</span>
            </Tag>
          </div>
        );
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "value5",
      title: "电池电压 v",
      width: 120,
      cell: ({ row }) => {
        if (row.status == 4) return "---";
        return <>{row.value5 ?? "---"}</>;
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "value2",
      title: "电机电流 mA",
      width: 120,
      cell: ({ row }) => {
        if (row.status == 4) return "---";
        return <>{row.value2 ?? "---"}</>;
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "count",
      title: "剩余油量 ml",
      width: 120,
      cell: ({ row }) => {
        // 进行计算 总规格 - （规格/总次数）* 当前次数
        if (row.status == 4) return "---";
        // 剩余油量= （capacity / workRange）* 当前次数
        if (row.value3) {
          return (
            (row.device?.deviceAttr?.capacity /
              row.device?.deviceAttr?.workRange) *
            row.value3
          )?.toFixed(1);
        } else {
          return "---";
        }
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "value3",
      title: "剩余次数",
      width: 120,
      cell: ({ row }) => {
        if (row.status == 4) return "---";
        return <>{row.value3 ?? "---"}</>;
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "value1",
      width: 120,
      title: "温度 ℃",
      cell: ({ row }) => {
        if (row.status == 4) return "---";
        if (row?.dtCode != 109) return <>{row.value1 ?? "---"}</>;
        // 判断显示温度是否存在
        if ("showTemp" in (row?.device?.deviceAttr || {})) {
          const showTemp = row.device?.deviceAttr.showTemp;
          return <>{showTemp ? (row.value1 ?? "---") : "---"}</>;
          // 处理 showTemp
        }
        return <>{"---"}</>;
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "value4",
      title: "是否油堵",
      cell: ({ row }) => {
        if (row.status == 4) return "---";
        return <>{(row.value4 ?? 0) == 0 ? "否" : "是"}</>;
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "state",
      title: "设备状态",
      cell: ({ row }) => {
        return getDeviceState(row);
      },
    },
    {
      align: "center",
      ellipsis: true,
      colKey: "time",
      title: "监测时间",
      cell: ({ row }) => {
        if (row.status == 4) return "---";
        return row.time ? dayjs(row.time).format("YYYY-MM-DD HH:mm:ss") : "---";
      },
    },
  ];
  const expandedRow: TableProps<IotPoint>["expandedRow"] = ({ row }) => {
    return (
      <div className="more-detail flex flex-row  ">
        <div className="w-24 flex flex-row justify-center items-center">
          <img src={greaseImg} className=" h-24 mr-3" />
        </div>
        <div className="p-2 w-1/2">
          <Descriptions
            column={2}
            size="small"
            bordered
            labelStyle={{
              width: 150,
            }}
          >
            <DescriptionsItem
              label="加脂机型号"
              content={row?.device?.deviceAttr?.model}
            />
            <DescriptionsItem
              label="润滑脂容量（ml）"
              content={row?.device?.deviceAttr?.capacity}
            />
            <DescriptionsItem
              label="加脂周期（天）"
              content={row?.device?.deviceAttr?.period}
            />
            <DescriptionsItem
              label="总加脂次数（次）"
              content={row?.device?.deviceAttr?.workRange}
            />
          </Descriptions>
        </div>
        <div className="w-1/2 pl-5 flex flex-row items-center">
          <Button
            theme="warning"
            size="small"
            variant="outline"
            onClick={() => {
              setVisible(true);
              setDeviceCode(row?.deviceCode);
            }}
          >
            手动加脂
          </Button>
        </div>
      </div>
    );
  };
  const rehandleExpandChange: TableProps["onExpandChange"] = (value) => {
    setExpandedRowKeys(value as string[]);
  };
  return (
    <>
      <Table<IotPoint>
        bordered
        data={dataSource}
        columns={columns}
        rowKey="id"
        verticalAlign="middle"
        hover
        expandedRowKeys={expandedRowKeys}
        expandedRow={expandedRow}
        expandOnRowClick={expandOnRowClick}
        // expandIcon={expandIcon === 'custom' ? tmpExpandIcon : expandIcon}
        onExpandChange={rehandleExpandChange}
        lazyLoad
        maxHeight={height ?? 700}
        scroll={{
          type: "lazy",
        }}
      />
      <Dialog
        visible={visible}
        header="温馨提示"
        body={
          <div className="w-full">
            <span className=" text-red-500">
              手动加脂需1-2分钟才能完成！，确定要手动加脂吗？
            </span>
            <Progress
              percentage={progress}
              className="w-full mt-5"
              strokeWidth={15}
              color={"#00a854"}
              label={progress < 100 ? `${progress}%` : resultText}
            ></Progress>
          </div>
        }
        closeBtn={false}
        confirmLoading={isRunning}
        cancelBtn={isRunning ? null : "关闭"}
        confirmBtn={isFinish ? null : "确定"}
        onConfirm={async () => {
          let res = await apiDevice.addGrease(deviceCode);
          if (res && res.code == 200) {
            setRecordId(res.data);
            setIsRunning(true);
          }
        }}
        onCancel={() => {
          setVisible(false);
          setProgress(0);
          setIsFinish(false);
          setResultText("");
        }}
      />
    </>
  );
};
export default GreaseTable;
